<template>
	<view class="add-address">
		<view class="add-form">
			<view class="form-item">
				<label>姓名</label>
				<input class="input" placeholder="姓名" v-model="address.userName" auto-focus />
			</view>
			<view class="form-item">
				<label>手机号码</label>
				<input class="input" v-model="address.mobile" placeholder="手机号码" />
			</view>
			<view class="form-item">
				<label>选择区域</label>
				<!-- APP、H5使用自定义组件，需要自己定期维护全国地市数据 region-picker.js-->
				<!-- #ifdef APP-PLUS || H5 -->
				<tui-region-picker mode="region" @change="bindRegionChange" v-model="region">
					<view class="picker">
						{{address.provinceName}}{{address.cityName}}{{address.countyName}}
					</view>
				</tui-region-picker>
				<!-- #endif -->
				<!-- 非APP、H5使用原生组件 -->
				<!-- #ifndef APP-PLUS || H5 -->
				<picker mode="region" @change="bindRegionChange" v-model="region">
					<view class="picker">
						{{address.provinceName}}{{address.cityName}}{{address.countyName}}
					</view>
				</picker>
				<!-- #endif -->
			</view>
      <view class="form-item">
        <label>详细地址</label>
        <input class="input" v-model="address.detailInfo" placeholder="详细地址, 如街道、楼盘号等" />
        <tui-icon name="location" @click="bingAddressTap" :size="26"></tui-icon>
      </view>
      <view class="form-item">
        <label>默认地址</label>
        <view @tap="bindIsDefault">
          <tui-checkbox :checked="address.isDefault === 1"></tui-checkbox>
        </view>
      </view>
		</view>

		<view class="btns">
			<button class="cannel" @tap="cancelAddress">取消</button>
			<button class="save" @tap="saveAddress">保存</button>
		</view>
	</view>
</template>

<script>
	const util = require("@/utils/util.js")
	const app = getApp();
	export default {
		data() {
			return {
				address: {
					id: '',
          provinceName: '安徽省',
          cityName: '合肥市',
          countyName: '蜀山区',
					provinceId: 0,
					cityId: 0,
					countyId: 0,
					detailInfo: '',
					userName: '',
					mobile: '',
					isDefault: 0
				},
				addressId: 0,
				region: ['安徽省', '合肥市', '蜀山区']
			}
		},
		methods: {
			saveAddress() {
				let address = this.address;

				if (address.userName.trim() == '') {
					util.toast('请输入姓名');
					return false;
				}

				if (!util.isMobile(address.mobile)) {
					util.toast('请输入正确的手机号码');
					return false;
				}

				if (address.countyName == 0) {
					util.toast('请输入省市区');
					return false;
				}

				if (address.detailInfo == '') {
					util.toast('请输入详细地址');
					return false;
				}

				let that = this;
				util.request('address/saveOrUpdate', {
					id: address.id,
					userName: address.userName.trim(),
					mobile: address.mobile,
					provinceName: address.provinceName,
					cityName: address.cityName,
					countyName: address.countyName,
					detailInfo: address.detailInfo,
					isDefault: address.isDefault,
					latitude: address.latitude,
					longitude: address.longitude,
				}, 'POST').then(function(res) {
					if (res.code === 0) {
						uni.navigateBack({
							fail() {
								uni.switchTab({
									url: '/pages/index/index',
								})
							}
						})
					}
				});
			},
			bindRegionChange: function(e) {
				var addr = this.address
				addr.provinceName = e.detail.value[0]
				addr.cityName = e.detail.value[1]
				addr.countyName = e.detail.value[2]
				addr.detailInfo = ''
				this.address = addr;
			},
			cancelAddress() {
				uni.navigateBack({
					fail() {
						uni.switchTab({
							url: '/pages/index/index',
						})
					}
				})
			},
			bingAddressTap: function() {
				var that = this;
				uni.chooseLocation({
					latitude: that.address.latitude,
					longitude: that.address.longitude,
					success: function(res) {
						if (null == res.latitude) {
							return;
						}
						that.latLong = {
							latitude: res.latitude,
							longitude: res.longitude
						};
            util.request('map/reverseGeocoder', {
              location: res.latitude + ',' + res.longitude
            }).then(function(rs) {
              if (rs.code === 0) {
                var address = that.address;
                address.provinceName = rs.result.address_component.province;
                address.cityName = rs.result.address_component.city;
                address.countyName = rs.result.address_component.district;
                address.detailInfo = rs.result.address_component.street + rs.result.address_reference.landmark_l2.title;
                address.latitude = res.latitude;
                address.longitude = res.longitude;
                that.address = address;
                if (address.provinceName && address.cityName && address.countyName) {
                  that.region = [address.provinceName, address.cityName, address.countyName];
                }
              }
            });
					}
				})
			},
			bindIsDefault() {
				let address = this.address;
				if (address.isDefault === 1) {
					address.isDefault = 0;
				} else {
					address.isDefault = 1;
				}
				this.address = address;
			},
			getAddressDetail() {
				let that = this;
				util.request('address/addressDetail', {
					id: that.addressId
				}).then(function(res) {
					if (res.code === 0 && null != res.data) {
						that.address = res.data
						that.latLong = {
							latitude: res.data.latitude,
							longitude: res.data.longitude
						};
					}
				});
			},
			initRegion() {
        let that = this;
        // #ifdef MP-WEIXIN
        uni.getFuzzyLocation({
          success: function(res) {
            that.reverseGeocoder(res)
          },
          complete() {},
          fail(rs) {
            console.log(rs);
          }
        });
        // #endif
        // #ifndef MP-WEIXIN
        uni.getLocation({
          success: function(res) {
            that.reverseGeocoder(res)
          },
          complete() {},
          fail(rs) {
            console.log(rs);
          }
        });
        // #endif
			},
      reverseGeocoder(res) {
        let that = this;
        util.request('map/reverseGeocoder', {
          location: res.latitude + ',' + res.longitude
        }).then(function(rs) {
          if (rs.code === 0) {
            var address = that.address;
            address.provinceName = rs.result.address_component.province;
            address.cityName = rs.result.address_component.city;
            address.countyName = rs.result.address_component.district;
            address.detailInfo = rs.result.address_component.street + rs.result.address_reference.landmark_l2.title;
            address.latitude = res.latitude;
            address.longitude = res.longitude;
            that.address = address;
            if (address.provinceName && address.cityName && address.countyName) {
              that.region = [address.provinceName, address.cityName, address.countyName];
            }
          }
        });
      }
		},
		onLoad: function(options) {
      let that = this;
      // 页面初始化 options为页面跳转所带来的参数
      if (options.id && options.id != '0') {
        that.addressId = options.id;
        that.getAddressDetail();
      } else {
        that.initRegion();
      }
		}
	}
</script>

<style lang="scss">
	page {
		height: 100%;
    font-size: 26rpx;
	}

	.add-address .add-form {
		background: #fff;
		width: 100%;
		height: auto;
		overflow: hidden;
	}

	.add-address .form-item {
		height: 100rpx;
		padding-left: 31.25rpx;
		border-bottom: 1px solid #d9d9d9;
		display: flex;
		align-items: center;
		padding-right: 31.25rpx;
	}

	.add-address label {
		width: 160rpx;
		font-weight: bold;
	}

	.add-address .input {
		flex: 1;
		height: 44rpx;
		line-height: 44rpx;
    font-size: 24rpx;
		overflow: hidden;
	}

	.add-address .btns {
		position: fixed;
		bottom: 0;
		left: 0;
		overflow: hidden;
		display: flex;
		height: 100rpx;
		width: 100%;
	}

	.add-address .cannel,
	.add-address .save {
		flex: 1;
		height: 100rpx;
		text-align: center;
		line-height: 100rpx;
		font-size: 28rpx;
		color: #fff;
		border: none;
		border-radius: 0;
	}

	.add-address .cannel {
		background: #333;
	}

	.add-address .save {
		background: $color-default;
	}

	.region-select {
		width: 100%;
		height: 600rpx;
		background: #fff;
		position: fixed;
		z-index: 10;
		left: 0;
		bottom: 0;
	}

	.region-select .hd {
		height: 108rpx;
		width: 100%;
		border-bottom: 1px solid #f4f4f4;
		padding: 46rpx 30rpx 0 30rpx;
	}

	.region-select .region-selected {
		float: left;
		height: 60rpx;
		display: flex;
	}

	.region-select .region-selected .item {
		max-width: 140rpx;
		margin-right: 30rpx;
		text-align: left;
		line-height: 60rpx;
		height: 100%;
		color: #333;
		font-size: 28rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.region-select .region-selected .item.disabled {
		color: #999;
	}

	.region-select .region-selected .item.selected {
		color: #b4282d;
	}

	.region-select .done {
		float: right;
		height: 60rpx;
		width: 60rpx;
		border: none;
		background: #fff;
		line-height: 60rpx;
		text-align: center;
		color: #333;
		font-size: 28rpx;
	}

	.region-select .done.disabled {
		color: #999;
	}

	.region-select .bd {
		height: 492rpx;
		width: 100%;
		padding: 0 30rpx;
	}

	.region-select .region-list {
		height: auto;
		overflow: scroll;
	}

	.region-select .region-list .item {
		width: 100%;
		height: 104rpx;
		line-height: 104rpx;
		text-align: left;
		color: #333;
		font-size: 28rpx;
	}

	.region-select .region-list .item.selected {
		color: #b4282d;
	}

	.bg-mask {
		height: 100%;
		width: 100%;
		background: rgba(0, 0, 0, 0.4);
		position: fixed;
		top: 0;
		left: 0;
		z-index: 8;
	}
</style>
